package org.chen.q6;

import java.io.Closeable;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;

public class SocketServer1 extends Thread {
    int port = 8801;

    public SocketServer1(){}

    public SocketServer1(int port){
        this.port = port;
    }

    @Override
    public void run() {
        ServerSocket server = null;
        try {
            server = new ServerSocket(port);
            while (true){
                Socket socket = server.accept();
                service(socket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(server);
        }
    }

    private void service(Socket socket) {
        SocketAddress socketAddress = socket.getRemoteSocketAddress();
        System.out.println("接收到来自"+socketAddress+"的请求");
        try {
            PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
            printWriter.println("HTTP/1.1 200 OK");
            printWriter.println("Content-Type:text/html;charset=utf-8");
            String body = "hello server1";
            printWriter.println("Content-Length:"+body.getBytes().length);
            printWriter.print("\r\n");
            printWriter.write(body);
            close(printWriter);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(socket);
        }
    }

    private static void close(Closeable closeable){
        if (closeable != null){
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        try {
            SocketServer1 server1 = new SocketServer1();
            server1.join();
            server1.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
